package vertx;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.vertx.java.core.AsyncResult;
import org.vertx.java.core.AsyncResultHandler;
import org.vertx.java.core.Future;
import org.vertx.java.core.Handler;
import org.vertx.java.core.MultiMap;
import org.vertx.java.core.VoidHandler;
import org.vertx.java.core.buffer.Buffer;
import org.vertx.java.core.eventbus.EventBus;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.http.HttpServer;
import org.vertx.java.core.http.HttpServerFileUpload;
import org.vertx.java.core.http.HttpServerRequest;
import org.vertx.java.core.http.RouteMatcher;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.core.logging.Logger;
import org.vertx.java.platform.Verticle;

public class ServerHttp extends Verticle {
	Logger logger = null;
	Route route = null;

    public void start(final Future<Void> startedResult) {
		logger = container.logger();
		
//		container.deployVerticle("vertx/WebClient.js");
//		container.deployVerticle("vertx/Route");
//		container.deployVerticle("WebClient.js",new AsyncResultHandler<String>() {
//		    public void handle(AsyncResult<String> deployResult) {
//		        if (deployResult.succeeded()) {
//					logger.info("Deploy vericle succesful!");
//		        } else {
//					logger.error(deployResult.cause());
//					//startedResult.setFailure(deployResult.cause());
//		        }
//		    }
//		});
		
		final EventBus eb = vertx.eventBus();

//		route = new Route(vertx, eb, logger);

		RouteMatcher rm = new RouteMatcher();
		rm.get("/eventbusbridge/index.html", new Handler<HttpServerRequest>() {
            public void handle(HttpServerRequest req) {
            	String staticPath = container.config().getString("static_files", System.getProperty("user.dir"));
            	logger.info("static path files " + staticPath);
            	req.response().sendFile("./webroot/eventbusbridge/index.html");
            }
		});
		rm.get("/vertxbus.js", new Handler<HttpServerRequest>() {
			public void handle(HttpServerRequest req) {
				req.response().sendFile("./webroot/js/vertxbus-2.1.js");
			}
		});
		rm.get("/tag/:tag", new Handler<HttpServerRequest>() {
            public void handle(HttpServerRequest req) {
            	logger.info("Richiesta ricevuta da " + req.remoteAddress());
            	logger.info("Metodo: " + req.method());
            	logger.info("Risorsa richiesta: " + req.uri());
            	
            	final HttpServerRequest request = req;
            	final String tag = req.params().get("tag");
            	eb.send("webclient_address", tag, new Handler<Message>() {
                    public void handle(Message message) {
                    	JsonObject jsRecords = new JsonObject((String)message.body());
                    	logger.info("Records: " + message.body());
                    	StringBuffer html = new StringBuffer();
                    	html.append("<html><body><h1>Results for ").append(tag).append("</h1>");
                    	for (int i = 0; i < jsRecords.getArray("items").size(); i++) {
                        	logger.info("Record: " + jsRecords.getArray("items").get(i));
                        	JsonObject jsRecord = jsRecords.getArray("items").get(i);
                    		html.append("<h3>").append(jsRecord.getString("title")).append("</h3>");
                    		html.append("<a href='").append(jsRecord.getString("link")).append("'>");
                    		html.append("<img src='").append(jsRecord.getString("media.m"));
                    		html.append("' /></a>");
                    		html.append(jsRecord.getString("description"));
						}
                    	html.append("</body></html>");
                    	// The webclient has returned a message!
//                    	var items = JSON.parse(message).items;
                    	
//                    	for (var i = 0; i < items.length; i++) {
//                    		html += "<h3>" + items[i].title + "</h3>";
//                    		html += "<a href="" + items[i].link + ""><img src="" + items[i].media.m + "" /></a>";
//                    		html += items[i].description;
//                    	}
                    	request.response().end(html.toString());
                    }
                });
            }
            	
       	});
		
		
//	    Vertx vertx = VertxFactory.newVertx();
		HttpServer server = vertx.createHttpServer();
		// Initialize the SockJS bridge
		vertx.createSockJSServer(server).bridge(new JsonObject("{prefix: '/eventbus'}"), new JsonArray("{address: 'webclient_address'}"), new JsonArray("{}"));

		server.requestHandler(rm).listen(8080,"localhost");
        

        
        
        		
//        		new Handler<HttpServerRequest>() {
//            public void handle(HttpServerRequest req) {
//
//            	logger.info("Richiesta ricevuta da " + req.remoteAddress());
//            	logger.info("Metodo: " + req.method());
//            	logger.info("Risorsa richiesta: " + req.uri());
//            	
//            	final HttpServerRequest request = req;
//            	final Buffer body = new Buffer(0);


            	
            	
//            	req.expectMultiPart(false);
//            	req.expectMultiPart(true);
//            	req.uploadHandler(new Handler<HttpServerFileUpload>() {
//            	    public void handle(HttpServerFileUpload upload) {
//                        logger.info("Ricezione file " + upload.filename());
//                        logger.info("Path del server " + request.path());
//            	    	upload.streamToFileSystem("../../"+upload.filename());
//            	    }
//            	});

//            	req.dataHandler(new Handler<Buffer>() {
//                    public void handle(Buffer buffer) {
//                    	body.appendBuffer(buffer);
//                        logger.info("Ricezione " + buffer.length() + " bytes");
//                    }
//                });

//            	req.endHandler(new VoidHandler() {
//                    public void handle() {
//                      // The entire body has now been received
//                      logger.info("Fine ricezione " + body.length() + " bytes");
//                      // The request has been all ready so now we can look at the form attributes
//                      MultiMap attrs = request.formAttributes();
//                      for (Iterator iterator = attrs.iterator(); iterator.hasNext();) {
//						Entry entry = (Entry) iterator.next();
//	                    logger.info(entry.getKey() + " " + entry.getValue());
//	                    // Do something with them
//                      }
//                    }
//                });

            	
            	
//                StringBuilder sb = new StringBuilder();
//                for (Entry<String, String> header: req.headers().entries()) {
//                    sb.append(header.getKey()).append(": ").append(header.getValue()).append("\n");
//                }
//                req.response().putHeader("content-type", "text/plain");
//                req.response().end(sb.toString());
//                String file = req.path().equals("/") ? "index.html" : req.path();
//                req.response().sendFile("webroot/" + file);
            	
//            	req.response().end();
//            }
//        }).listen(8080, "localhost"
//	        	, new AsyncResultHandler<Void>() {
//	            public void handle(AsyncResult<HttpServer> asyncResult) {
//	                logger.info("Listen succeeded? " + asyncResult.succeeded());
//	            }
//	        }
//        );
        // Prevent the JVM from exiting
//	    try {
//			System.in.read();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
        
    }
 
    public static void main(String[] args) throws Exception {
    	new ServerHttp().start();
    }
   
}